/*
 * 账户管理
 * @author 狮子
 * @time 2018/11/9
 * @since 1.0.0
 * */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form, Row, Col, Input, Cascader,  Select, Button, } from 'antd'
const FormItem = Form.Item;
const { TextArea } = Input;
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
import cx from 'classnames'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './accountDetailStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { makeAddress } from "utils/util"

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 15 },
};
const ItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};
const routeView = function ({ dispatch, model, form }) {

  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  const { modelObj, namespace } = model
  let { areaList, areas, accountDetail, actionType, estateList,disabled,bankCodeList,area1,products,roleType,show} = modelObj
  console.log(modelObj)
  debugger
  // 省级改变时
  function onChange(value,type,selectedOptions) {
    if(type=='location'){
      accountDetail.province = value[0]
      accountDetail.city = value[1]
      new Promise((resolve) => {
        dispatch({
          type: `${namespace}/getEstateList`,
          payload: { province: value[0], city: value[1], resolve }
        })
      }).then((res) => {
        console.log(res)
  
      })
    }else if(type=='bankLocation'){
      accountDetail.bankProvince = value[0]
      accountDetail.bankCity = value[1]
      accountDetail.bankProvinceName = selectedOptions[0].label
      accountDetail.bankCityName = selectedOptions[1].label
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { accountDetail }
    });
  }
  // 获取项目选项
  function getPorjectOption() {
    return estateList.map((item, idx) => {
      return <Select.Option key={idx} value={item.productId}>{item.name}</Select.Option>
    })
  }
  //银行列表
  function getBankListOption(){
    return bankCodeList.map((item,idx)=>{
      return  <Select.Option key={idx} value={item.bankCode}>{item.bankName}</Select.Option>
    })
  }
  //输入框改变时
  function inputChange(e, type, value) {
    console.log(type)
    if(type=='regionId'){
			area1.map((item,index)=>{
        console.log(item,'item')
				if(item.value==e){
					if(item.children.length){
            areas = makeAddress(item.children,2)
            areas.shift()
          }
          show = item.productIdAll
				}
      })
      if(e==0){
        areas=[]
        accountDetail.productId=""
        accountDetail.name=''
      }
      accountDetail.city=null
      accountDetail.province=null
      products=[]
    }else if(type=='cityCode'){
      accountDetail.productId=""
      accountDetail.name=''
      accountDetail.city=e[1]
      accountDetail.province=e[0]
      if(value&&value.length>0){
        accountDetail.cityName=value[1].label
        accountDetail.provinceName=value[0].label
      }
      products=[]
    }
    accountDetail[type] = e
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { accountDetail,areas,products,show}
    });
    console.log(e, type)
  }
  //提交
  function sumbit() {
    form.validateFields((err, values) => {
      if(!err){
        dispatch({
          type: `${namespace}/sumbit`,
          payload: values
        })
      }
    });
  }
  return (
    <div className={cx('pageLayout')}>
      <div className={cx('public_listMain')}>
        <div className="functionButton">
          {/* <Button type='primary'>预览</Button> */}
          {actionType == "add" || actionType == "edit" ?<Button type='primary' onClick={e => sumbit()} disabled={disabled}>提交</Button>
            : null}
        </div>
      </div>
      <CollapsiblePanels title="账户信息" hideUpDownBtn={true} >
        <Row>
          <Col span={6}>
            <FormItem {...formItemLayout} label='所属区域'>
            {getFieldDecorator('regionId',{
                    initialValue: accountDetail.regionId ? accountDetail.regionId:(roleType==1?'0':''),
                    rules: [
                      { required:true,whitespace: true, message: '请选择所属城市'},
                    ],
                })(
                <Select placeholder='请选择区域'  onChange={e=>{
                  setFieldsValue({productId:'',province:[]})
                  inputChange(e,'regionId')
                 
                }}>
                  {
                    roleType==1?<Select.Option key='0' value='0'>集团</Select.Option>:null
                  }
                  
                  {area1.map((item)=>{
                    return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                  })}
                </Select>)}
              </FormItem>
          </Col>
          <Col span={6}>
            <FormItem {...formItemLayout}  label='所属城市'>
                  {getFieldDecorator('province', {
                          initialValue: accountDetail.cityCode,
                          rules: [
                            { required:roleType==3 || !show?true:false, message: '请选择所属城市' },
                          ],
                      })(
                <Cascader placeholder='请选择城市'  options={areas}  onChange={(e,value)=>{
                  setFieldsValue({productId:''})
                    inputChange(e,'cityCode',value)} }>
                </Cascader>
              )}
            </FormItem>
          </Col>
          <Col span={6}>
            <FormItem {...formItemLayout}  label='所属项目'>
              {getFieldDecorator('productId', {
                      initialValue:accountDetail.productId,
                      rules: [
                        { required:roleType==3 || !show || accountDetail.city ?true:false,whitespace: true, message: '请选择所属项目' },
                      ],
                  })(
                <Select placeholder='请选择项目'  onChange={e=>{
                    inputChange(e,'productId') 
                  }} onFocus={()=>{
                        dispatch({
                          type:`${namespace}/getProduct`,
                          payload:{}
                        })
                    }								
                  }>
                  {products.map((item)=>{
                    return <Select.Option  value={item.value}>{item.label}</Select.Option>
                  })}
                </Select>)}
            </FormItem>
        </Col>
        </Row>
        <Row>
          <Col className="col" span={12}>
            <FormItem {...ItemLayout}
              label="账户类型">
              {getFieldDecorator(`type`, {
                initialValue: accountDetail.type+'' || '',
                rules: [
                  { required: true, whitespace: true, message: '请输入账户类型' },
                ],
              })(
              // <Input placeholder={'请输入账户类型'} disabled  />
              <Select onChange={e=>{
                inputChange(e,'type')
              }}>
                <Select.Option value='1'>
                  公户
                </Select.Option>
                <Select.Option value='2'>
                  私户
                </Select.Option>
              </Select>
              )}
            </FormItem>
          </Col>
          <Col className="col" span={12}>
            <FormItem {...formItemLayout}
              label="账户名称">
              {getFieldDecorator(`accountName`, {
                initialValue: accountDetail.accountName,
                rules: [
                  { required: true, whitespace: true, message: '请输入账户名称' },
                ],
              })(<Input placeholder={'请输入账户名称'} disabled={actionType == 'check'} onChange={(e) => inputChange(e.target.value, 'accountName')} />)}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col className="col" span={12}>
            <FormItem {...ItemLayout}
              label="银行账号">
              {getFieldDecorator(`bankAccount`, {
                initialValue: accountDetail.bankAccount,
                rules: [
                  { required: true, whitespace: true, message: '请输入银行账号' },
                ],
              })(<Input placeholder={'请输入银行账号'} disabled={actionType == 'check'} onChange={(e) => inputChange(e.target.value, 'bankAccount')} />)}
            </FormItem>
          </Col>
          <Col className="col" span={12}>
            <FormItem {...formItemLayout}
              label="所属银行">
              {getFieldDecorator(`bankCode`, {
                initialValue: accountDetail.bankCode,
                rules: [
                  { required: true, whitespace: true, message: '请选择所属银行' },
                ],
              })(<Select
                notFoundContent={'暂无数据'}
                disabled={actionType == 'check' }
                placeholder="请选择银行"
                onChange={(e, idx) => inputChange(e, 'bankCode', idx)} >
                {getBankListOption()}
              </Select>)}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col className="col" span={12}>
            <FormItem {...ItemLayout}
              label="开户行城市">
              {getFieldDecorator(`bankLocation`, {
                initialValue: [`${accountDetail.bankProvince}`, `${accountDetail.bankCity}`],
                rules: [
                  {
                    required: true, validator: (rule, value, callback) => {
                      //console.log(accountDetail.city)
                      if (typeof (accountDetail.bankCity || accountDetail.bankProvince) == 'undefined') {
                        callback('请选择所属城市')
                      } else {
                        callback()
                      }
                    }
                  }
                ],
              })( <Cascader options={areaList} placeholder="请选择开户行城市" disabled={actionType == 'check' } onChange={(e, selectedOptions)=>onChange(e,'bankLocation', selectedOptions)} />)}
            </FormItem>
          </Col>
          <Col className="col" span={12}>
            <FormItem {...formItemLayout}
              label="开户支行">
              {getFieldDecorator(`bankAccountName`, {
                initialValue: accountDetail.bankAccountName,  
                rules: [
                  { required: true, whitespace: true, message: '请输入开户支行' },
                ],
              })(<Input placeholder={'请输入开户支行'} disabled={actionType == 'check'} onChange={(e) => inputChange(e.target.value, 'bankAccountName')} />)}
            </FormItem>
          </Col>
        </Row>

      </CollapsiblePanels>
    </div>
  )
}
// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))